<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
              <select-project-input ref="projectInput" :disabled="formDisabled" v-model="model.projectId" :proDisabled="true" :allowClear="false" placeholder="请输入选择项目" :projectStatus="'2'" @input="projectChangeHandle" />
<!--              @input="selectProject"-->
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
<!--              <a-input :disabled=formDisabled v-model="model.year" :max-length="36"  placeholder="请输入业绩归属年度" disabled  ></a-input>-->
              <j-dict-select-tag type="list" v-model="model.year" dictCode="yjgsnd" placeholder="请选择业绩归属年度" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="签订单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signUnit">
              <select-Company-input :disabled="true" v-model="model.signUnit" placeholder="请选择签订单位" disabled/>
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="8">-->
<!--            <a-form-model-item label="业务名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryName">-->
<!--              <a-input :disabled=formDisabled v-model="model.categoryName" :max-length="36"  placeholder="请输入业务名称"  ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
          <a-col :span="8">
            <a-form-model-item label="业务名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskId">
              <select-task-file-input v-model="model.taskId" :projectId="model.projectId" :isShowCategoryName="true" :isExcludeWaitingStatus="true" @input="taskChangeBackHandle"/>

            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="费用所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="feeTeamId">
              <select-team-input :disabled=formDisabled v-model="model.feeTeamId" :tdlx="3" @back="feeTeamChangeBackHandle"/>
<!--              <a-input :disabled=formDisabled v-model="model.relfeeTeamId" :max-length="36"  placeholder="请输入业务名称" @inpupt="feeTeamChangeBackHandle" :hidden="true"  ></a-input>-->
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="费用所属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="feeYear">
<!--              <a-input :disabled=formDisabled v-model="model.feeYear" :max-length="36"  placeholder="请输入费用所属年度"  ></a-input>-->
              <j-dict-select-tag :disabled=formDisabled type="list" v-model="model.feeYear" dictCode="tdnd_type" placeholder="请选择费用所属年度" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="合同额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractAmount">
              <a-input-number :disabled=formDisabled :max="999999999" :min="0" :precision="2" v-model="model.contractAmount" placeholder="请输入合同额" style="width: 100%" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="分配合同额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskContractAmount">
              <a-input-number :disabled=formDisabled :max="999999999" :min="0" :precision="2" v-model="model.taskContractAmount" placeholder="请输入分配合同额" style="width: 100%" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="回款额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="realCollectionPaymentMoney">
              <a-input-number :disabled=formDisabled :max="999999999" :min="0" :precision="2" v-model="model.realCollectionPaymentMoney" placeholder="请输入回款额" style="width: 100%" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="审批级别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalLevel">
<!--              <a-input :disabled=formDisabled v-model="model.approvalLevel" :max-length="36"  placeholder="请输入审批级别"  ></a-input>-->
              <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.approvalLevel" dictCode="approval_level" placeholder="请选择审批级别" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="难易程度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="difficultyLevel">
<!--              <a-input :disabled=formDisabled v-model="model.difficultyLevel" :max-length="36"  placeholder="请输入难易程度"  ></a-input>-->
              <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.difficultyLevel" dictCode="industry_coefficient" placeholder="请选择难易程度" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="任务进度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="progressName">
              <a-input :disabled=formDisabled v-model="model.progressName" :max-length="36"  placeholder="请输入任务进度" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="报告编制绩效（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reportAchievements">
              <a-input-number :disabled=formDisabled :max="999999999" :min="0" :precision="2" v-model="model.reportAchievements" placeholder="请输入报告编制绩效" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="绩效提取金额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="achievementsMoney">
              <a-input-number :disabled=formDisabled :max="999999999" :min="0" :precision="2" v-model="model.achievementsMoney" placeholder="请输入绩效提取金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
  import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
  import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
  import SelectTaskFileInput from '@/views/scy/components/SelectTaskFileInput'
  import moment from 'moment'
  import { mapGetters } from 'vuex'
  import SelectProjectTaskInput from '@/views/scy/components/SelectProjectTaskInput.vue';
  import {pushIfNotExist, randomNumber, randomUUID} from '@/utils/util'

  export default {
    name: 'ErpAchievementsExtractionDtForm',
    components: {
      SelectProjectTaskInput,
      SelectUserByDep,
      SelectTeamInput,
      SelectCompanyInput,
      SelectCustomerInput,
      SelectProjectInput,
      SelectTaskFileInput
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        flag: false,
        model:{
         },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          projectId: [
            { required: true, message: '请选择项目名称!'},
          ],
          taskId: [
            { required: true, message: '请选择业务名称!'},
          ],
          feeTeamId: [
            { required: true, message: '请选择费用所属团队!'},
          ],
          reportAchievements: [
            { required: true, message: '请输入报告编制绩效!'},
          ],
          achievementsMoney: [
            { required: true, message: '请输入绩效提取金额!'},
          ],


        },
        url: {
          add: "/api/erp/omc/task/achievementsextraction/erpAchievementsExtractionDt/add",
          edit: "/api/erp/omc/task/achievementsextraction/erpAchievementsExtractionDt/edit",
          queryById: "/api/erp/omc/task/achievementsextraction/erpAchievementsExtractionDt/queryById",
          queryTeamById: "/api/erp/omc/teammanager/erpOmcTeamManager/queryById",
          // 收款进度
          queryProgressPaymentlist: '/api/erp/progress/erpProgressPayment/list',
          listAllNoPermission: '/api/erp/progress/erpProgressPayment/listAllNoPermission',
          // 任务进度
          queryProgressTaskProjectList: '/api/erp/progress/erpProgressTask/progressList'
        },
        tempProjectId: null,
        modelNew: {}
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      ...mapGetters(['userInfo']),
      add () {
        this.modelNew  = {}
        this.edit(this.modelDefault,'1');
      },
      edit (record,addFlag) {
        this.$refs['form'].clearValidate();
        // this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        // this.modelNew = Object.assign({}, record);

        if (addFlag === '1'){
          //是新增直接给空
          this.modelNew  = {}
          //备份数据已置空
        }else {
          //是编辑将model备份
          this.modelNew = JSON.parse(JSON.stringify(record));
        }

        this.visible = true;
      },

      async projectChangeHandle(item){
          // 项目切换重新带数据
          // if (item.choseObj[0].id !== this.tempProjectId ){
          // if (this.modelNew.projectId && item.choseObj[0].id !== this.modelNew.projectId){
          if (JSON.stringify(this.modelNew) === '{}' || this.modelNew.projectId && item.choseObj[0].id !== this.modelNew.projectId){
            // this.tempProjectId = null
            //清除项目数据
            this.resetDate();
            //清除任务
            this.$set(this.model,'taskId',null)

            //带出业绩归属年度
            this.$set(this.model,'year',item.choseObj[0].year)
            //带出签订单位
            this.$set(this.model,'signUnit',item.choseObj[0].signUnit)

            //带出合同总额和实收款总额
            await getAction(this.url.listAllNoPermission, {projectId: item.choseObj[0].id, contractType: '1'}).then((res) => {
              if (res.success) {
                let temp = res.result.records.length === 0 ? '没有收款合同哦！' : '有收款合同的'
                //如果有项目收款合同
                if (res.result.records.length > 0){
                  //带出合同额
                  this.$set(this.model,'contractAmount',res.result.records[0].contractTotalMoney)
                  //带出回款额
                  this.$set(this.model,'realCollectionPaymentMoney',res.result.records[0].realCollectionPaymentMoney)
                }else { //没有收款合同则合同额和回款额置空
                  //清除合同额
                  this.$set(this.model,'contractAmount',null)
                  //清除回款额
                  this.$set(this.model,'realCollectionPaymentMoney',null)
                }
              }
            })
              // this.modelNew = Object.assign({}, this.model);
            this.modelNew = JSON.parse(JSON.stringify(this.model));


          }


      },
      //清空数据
      resetDate(type = '99999') {
        // 清空任务带出的数据
        if (type === '1') {
          this.$set(this.model, 'feeTeamId', null)
          this.$set(this.model, 'feeYear', null)
          this.$set(this.model, 'progressName', null)
          this.$set(this.model, 'taskContractAmount', null)
          this.$set(this.model, 'difficultyLevel', null)
          this.$set(this.model, 'approvalLevel', null)
        } else if (type === '2') {
          // 清空项目带出的数据
          this.$set(this.model, 'year', null)
          this.$set(this.model, 'signUnit', null)
          this.$set(this.model, 'contractAmount', null)
          this.$set(this.model, 'realCollectionPaymentMoney', null)
        } else {
          // 清空所有带出的数据
          this.$set(this.model,'feeTeamId', null)
          this.$set(this.model,'feeYear',null)
          this.$set(this.model,'progressName',null)
          this.$set(this.model,'taskContractAmount',null)
          this.$set(this.model,'difficultyLevel',null)
          this.$set(this.model,'approvalLevel',null)
          this.$set(this.model,'year',null)
          this.$set(this.model,'signUnit',null)
          this.$set(this.model,'contractAmount',null)
          this.$set(this.model,'realCollectionPaymentMoney',null)
        }
      },

      taskChangeBackHandle(item) {
        if (item.choseObj[0]) {
          // this.tempProjectId = this.model.projectId
          // 先清空任务带出的数据
          this.resetDate('1');
          // 带出费用所属团队
          // this.$set(this.model,'feeTeamId',item[0].productTeam)
          this.$set(this.model,'feeTeamId',item.choseObj[0].productTeam)

          // 带出费用团队时也带出团队年度
          getAction(this.url.queryTeamById, { id: item.choseObj[0].productTeam }).then((res) => {
            if (res.success) {
              this.$set(this.model,'feeYear',res.result.tdnd)
            }
          })
          // 带出任务进度中任务进度名称
          getAction(this.url.queryProgressTaskProjectList, { projectTaskId: item.choseObj[0].id }).then((res) => {
            if (res.success) {
              if (res.result.records.length > 0) {
                this.$set(this.model,'progressName', res.result.records[0].taskProgress)
              }else {
                this.$set(this.model,'progressName',null)
              }
            }
          })

          //带出分配合同额
          this.$set(this.model,'taskContractAmount',item.choseObj[0].contractAmount)

          //带出复杂程度
          this.$set(this.model,'difficultyLevel',item.choseObj[0].complexity)

          //带出审批级别
          this.$set(this.model,'approvalLevel',item.choseObj[0].approvalLevel)
        } else {
          // 清空
          this.resetDate('1');
        }

      },
      // 手动选择费用所属团队带出团队年度
      feeTeamChangeBackHandle(item) {
        this.$set(this.model, 'feeYear', item[0].tdnd)
      },


      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            // 如果没有id就生成一个uuid
            if (!this.model.id) {
              this.model.id = randomUUID();
            }
            that.$emit('ok', this.model, this.flag);
          }
        })
      },
    }
  }
</script>
